package controllers

import (
	"encoding/json"
	"supershare/backend/models"

	"github.com/beego/beego/v2/server/web"
)

// VenueTypeController 场地类型管理控制器
type VenueTypeController struct {
	web.Controller
}

// VenueTypeCreateRequest 创建场地类型请求参数
type VenueTypeCreateRequest struct {
	Name      string `json:"name"`
	SortOrder int    `json:"sort_order"`
	Status    int8   `json:"status"`
}

// GetAll 获取所有场地类型
func (c *VenueTypeController) GetAll() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取场地类型，按加盟商ID过滤
	venueTypes, err := models.GetAllVenueTypes(permResult.Admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取场地类型失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取场地类型成功",
		"data":    venueTypes,
	}
	c.ServeJSON()
}

// Create 创建场地类型
func (c *VenueTypeController) Create() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	var req VenueTypeCreateRequest
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 创建场地类型
	venueType := &models.VenueType{
		Name:      req.Name,
		SortOrder: req.SortOrder,
		Status:    req.Status,
	}
	venueType.FranchiseId = permResult.Admin.FranchiseId
	// 设置创建者信息
	venueType.CreatedBy = permResult.Admin.Username
	venueType.UpdatedBy = permResult.Admin.Username
	venueType.BeforeInsert()

	// 保存到数据库
	id, err := models.CreateVenueType(venueType)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建场地类型失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "创建场地类型成功",
		"data": map[string]interface{}{
			"id": id,
		},
	}
	c.ServeJSON()
}
